package com.sk.util;

import jakarta.annotation.PostConstruct;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * Spring框架工具的快捷调用。
 *
 * @author smy
 * {@code @date} 2023/2/10
 */
@Component
@Slf4j
public class SpringUtil {
    private final MessageSource messageSource;
    private final Environment environment;
    @Getter
    private static String application;

    public SpringUtil(MessageSource messageSource, Environment environment) {
        this.messageSource = messageSource;
        this.environment = environment;
    }

    private static SpringUtil util;

    @PostConstruct
    public void init() {
        log.info("SpringUtil组件初始化");
        util = this;
        application = getProperty("spring.application.name");
    }


    public static String getProperty(String key) {
        return getProperty(key, null);
    }

    public static String getProperty(String key, String defValue) {
        if (util != null) {
            String value = util.environment.getProperty(key);
            return value == null ? defValue : value;
        }
        return defValue;
    }

    public static String getMessage(String code, String defaultMessage, Object[] args, Locale locale) {
        return util.messageSource.getMessage(code, args, defaultMessage, locale);
    }

    public static String getMessage(String code, String defaultMessage, Object... args) {
        return getMessage(code, defaultMessage, args, LocaleContextHolder.getLocale());
    }

}
